<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="../static/elderlyInfo/main/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../static/elderlyInfo/main/css/thesame.css" media="all">
    <link rel="stylesheet" href="../static/elderlyInfo/main/css/footer.css" media="all">
    <link rel="stylesheet" href="../static/elderlyInfo/css/rightCon.css" media="all">
    <link rel="stylesheet" href="../static/elderlyInfo/css/page.css" media="all">
    <link rel="stylesheet" href="../static/elderlyInfo/css/popCss.css" media="all">
    <style type="text/css">
        .layui-table-header input {
            width: 250px;
            margin: 5px auto;
        }
    </style>
</head>

<body class="layui-layout-body">
	<input type="hidden" id="userNo" th:value="${userNo}">
<div class="layui-body">
    <div class="add-title pad25px">
			<span class="mr10px cursor" onclick="back()">
				<img src="../static/elderlyInfo/img/return_icon.png">
			</span>
        <span>新建角色</span>
    </div>
    <!-- 内容主体区域 -->
    <!-- <div class="layui-box-con layui-box-con-posi relative"> -->
    <!-- <div class="layui-left-con layui-left-label-con layui-left-con-bot pad12px">
        <div class="border-radius4 bgWhite box-shadows">
            <div class="new-add-box-scroll">
                <nav class="label-nav-con">
                    <p class="f16px lh40px" style="padding-left: 33px;">全部</p>
                    <ul class="lh40px f14px">
                        <li class="current">床位费</li>
                        <li>护理费</li>
                        <li>长护险补贴</li>
                        <li>认知情况</li>
                        <li>居家情况</li>
                        <li>认知情况</li>
                    </ul>
                </nav>
            </div>
        </div>
    </div> -->
    <!-- <div class="layui-right-con layui-right-label-con layui-right-con-bot"> -->
    <div class="new-add-box new-add-box-width bgWhite box-shadows border-radius4">
        <div class="add-box-scroll">
            <!-- <div class="border-radius4 bgWhite box-shadows">
                <div class="new-add-box-scroll"> -->
            <div class="mar25px">
                <div class="mb25px">
                    <div class="new-add-title relative overflow mb15px"><span class="ml15px">基本信息</span></div>
                    <div class="new-add-con new-add-form pb25px border-bot1px">
                        <article class="new-add-left new-add-form-con">
                            <ul class="overflow">
                                <li>
                                    <p><label><em class="red">*</em>姓名：</label></p>
                                    <p><input type="text" id="userName" placeholder="请输入" class="layui-input"></p>
                                </li>
                                <li class="layui-form">
                                    <p><label>认知：</label></p>
                                    <p>
                                        <span><input type="radio" name="cognitionStatus" checked="checked" value="0"
                                                     title="否"></span>
                                        <span><input type="radio" name="cognitionStatus" value="1" title="是"></span>
                                    </p>
                                </li>
                                <li>
                                    <p><label><em class="red">*</em>民族 ：</label></p>
                                    <p>
                                        <select id="nation" class="form-select">
                                            <option value="">请选择</option>
                                            <option th:each="list:${pageData.nationList}" th:value="${list.labelCode}"
                                                    th:text="${list.labelName}"></option>
                                        </select>
                                    </p>
                                </li>
                                <li>
                                    <p><label><em class="red">*</em>户籍类型：</label></p>
                                    <p>
                                        <select id="householdRegister" class="form-select">
                                            <option value="">请选择</option>
                                            <option th:each="list:${pageData.householdRegisterList}"
                                                    th:value="${list.labelCode}" th:text="${list.labelName}">
                                            </option>
                                        </select>
                                    </p>
                                </li>
                                <li>
                                    <p><label><em class="red">*</em>身份证号：</label></p>
                                    <p><input id="userPid" th:value="${userPid}" onBlur="setAgeOfInput()" type="text"
                                              placeholder="请输入" class="layui-input"></p>
                                </li>
                                <li>
                                    <p><label><em class="red">*</em>性别：</label></p>
                                    <p>
                                        <select id="userSex" class="form-select">
                                            <option value="">请选择</option>
                                            <option value="1">男</option>
                                            <option value="2">女</option>
                                        </select>
                                    </p>
                                </li>
                                <li>
                                    <p><label>年龄：</label></p>
                                    <p><input id="age" type="text" placeholder="年龄" class="layui-input" disabled="">
                                    </p>
                                </li>
                                <li>
                                    <p><label>文化程度：</label></p>
                                    <p>
                                        <select id="education" class="form-select">
                                            <option value="">请选择</option>
                                            <option th:each="list:${pageData.educationList}"
                                                    th:value="${list.labelCode}" th:text="${list.labelName}"></option>
                                        </select>
                                    </p>
                                </li>
                                <li>
                                    <p><label>籍贯：</label></p>
                                    <p><input id="nativePlace" type="text" placeholder="请输入" class="layui-input"></p>
                                </li>
                                <li class="width-two">
                                    <p><label><em class="red">*</em>家庭地址：</label></p>
                                    <p><input id="liveAddress" type="text" placeholder="请输入" class="layui-input"></p>
                                </li>
                                <li>
                                    <p><label><em class="red">*</em>社保类型：</label></p>
                                    <p>
                                        <select id="socialSecurityType" class="form-select">
                                            <option value="">请选择</option>
                                            <option th:each="list:${pageData.socialSecurityTypeList}"
                                                    th:value="${list.labelCode}" th:text="${list.labelName}"></option>
                                        </select>
                                    </p>
                                </li>
                                <li>
                                    <p><label><em class="red">*</em>社保卡号：</label></p>
                                    <p><input id="socialSecurityCardNo" type="text" placeholder="请输入"
                                              class="layui-input"></p>
                                </li>
                                <li>
                                    <p><label>工作单位：</label></p>
                                    <p><input id="retireCompany" type="text" placeholder="请输入" class="layui-input"></p>
                                </li>
                                <li>
                                    <p><label>职业：</label></p>
                                    <p><input id="occupation" type="text" placeholder="请输入" class="layui-input"></p>
                                </li>
                            </ul>
                        </article>
                        <article class="new-add-right">
                            <dl class="inline-block relative">
                                <dt>
                                    <p class="filejs"><img src="../static/elderlyInfo/img/moren.png" id="imgPath"
                                                           class="bock"></p>
                                    <!-- <input type="file" class="hidden file" /> -->
                                    <input type="file" id="file_input" class="hidden file"/>
                                </dt>
                                <dd class="white lh30px textCenter">默认头像</dd>
                            </dl>
                        </article>
                    </div>
                </div>
                <div class="mb25px">
                    <div class="new-add-title relative overflow mb15px"><span class="ml15px">紧急联系人</span></div>
                    <div class="pb20px border-bot1px">
                        <!-- <div class="mt25px mb15px lh32px overflow add-btn-input">
                            <p class="left cursor">
                                <span class="white border-radius4 bgGreen inline-block pl15px pr15px"><img src="../static/elderlyInfo/img/button_add.png">添加</span>
                            </p>
                        </div> -->
                        <div class="border1px border-radius4">
                            <!-- <table class="layui-hide" id="test1" lay-filter="test"></table> -->
                            <table class="layui-table layui-table-header">
                                <thead>
                                <tr>
                                    <th>姓名</th>
                                    <th><span class="red">*</span>手机号码</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr>
                                    <td><input type="text" id="contactName1" placeholder="请输入姓名" class="layui-input">
                                    </td>

                                    <td><input type="text" id="mobile1" placeholder="请输入手机号" class="layui-input"></td>
                                </tr>
                                <tr>
                                    <td><input type="text" id="contactName2" placeholder="请输入姓名" class="layui-input">
                                    </td>

                                    <td><input type="text" id="mobile2" placeholder="请输入手机号" class="layui-input"></td>
                                </tr>

                                <tr>
                                    <td><input type="text" id="contactName3" placeholder="请输入姓名" class="layui-input">
                                    </td>

                                    <td><input type="text" id="mobile3" placeholder="请输入手机号" class="layui-input"></td>
                                </tr>
                                <tr>
                                    <td><input type="text" id="contactName4" placeholder="请输入姓名" class="layui-input">
                                    </td>

                                    <td><input type="text" id="mobile4" placeholder="请输入手机号" class="layui-input"></td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
            </div>
        </div>
    </div>
    <!-- </div> -->
    <!-- </div> -->
</div>
<div class="layui-footer layui-footer-one">
    <div class="btn-con textCenter">
        <span class="btn-one cursor" onclick="back()">取&nbsp;消</span>
        <span class="btn-two cursor" onclick="confirmAdd()">提&nbsp;交</span>
    </div>
</div>


<script src="../static/elderlyInfo/main/js/jquery-2.1.3.min.js"></script>
<script src="../static/elderlyInfo/main/layui/layui.js" charset="utf-8"></script>
<script>
    $(function () {

        layui.use(['element', 'form', 'laydate', 'layer'], function () {
        });

        //选中样式
        $('.label-nav-con li').click(function () {
            $(this).addClass('current').siblings().removeClass('current');
        })
        $(".filejs").click(function () {
            $(".file").click();
        })
        //上传图片
        document.getElementById("file_input").addEventListener('change', readFile, false);

        //初始化加载老人数据
        loadElderlyInfo();


    });


    function readFile() {
        var input = document.getElementById("file_input");
        var dataArr = []; // 储存所选图片的结果(文件名和base64数据)

        var fd = new FormData();
        var iLen = this.files.length;
        var index = 0;
        for (var i = 0; i < iLen; i++) {
            if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)) {　　//判断上传文件格式
                layer.msg('上传的图片格式不正确，请重新选择', {time: 3000});
                //        	layer.open({
                // 	content: '上传的图片格式不正确，请重新选择'
                // 	,skin: 'msg'
                // 	,time: 2 //2秒后自动关闭
                // });
                return;
            }
            var reader = new FileReader();
            reader.index = i;
            //fd.append(i,this.files[i]);
            fd.append("file", this.files[i]);
            sendImage(fd);//传送图片
            reader.readAsDataURL(this.files[i]);  //转成base64
            reader.fileName = this.files[i].name;
            //var imageName2=

            //console.log("====="+imageName2);
            reader.onload = function (e) {
                var imgMsg = {
                    name: this.fileName,//获取文件名
                    base64: this.result   //reader.readAsDataURL方法执行完后，base64数据储存在reader.result里
                }
                dataArr.push(imgMsg);
                $('#imgPath').attr('src', imgMsg.base64); //图片链接（base64）
            }


        }
    }

    function sendImage(fd) {
        $.ajax({
            url: '../img/uploadImage',
            type: 'post',
            data: fd,//JSON.stringify(submitArr),
            dataType: 'json',
            cache: false,
            processData: false,   //用FormData传fd时需有这两项     必要
            contentType: false,    //必要
            async: true,
            beforeSend: function () {
                layer.load(2);
            },
            success: function (res) {
                layer.closeAll();
                if (res.code == "0000") {
                    $('#imgPath').attr('value', res.msg); //图片链接（base64）
                    //$('#imgPath').attr('src', res.msg); //图片链接（base64）
                } else {
                    return layer.msg("图片上传失败，请重试", {time: 2000});
                }
            }
        });
    }


    //输入身份证号失去焦点 更改年龄
    function setAgeOfInput() {
        var userPid = $("#userPid").val();
        if (userPid.length == 18) {
            var age = getAgeByIdCard(userPid);
            $("#age").val(age);
        } else {
            $("#age").val("");
        }
    }

    //初始化老人档案信息 如果身份证号存在
    function loadElderlyInfo() {
        var userNo = $("#userNo").val();
        if (isNull(userNo)) {
            return;
        }

        var formDate =
            {
                userNo: userNo
            };

        $.ajax({
            url: "../elderlyInfo/getElderlyInfoByUserNo",
            type: "post",
            dataType: "json",
            data: formDate,
            async: false,
            success: function (res) {
                if (res.code == "200") {
                    // console.log(res);
                    var elderlyInfo = res.data;
                    if (isNull(elderlyInfo)) {
                        return;
                    }
                    $("#userName").val(elderlyInfo.userName);//姓名
                    $("#userSex").val(elderlyInfo.userSex);//性别
                    $("#householdRegister").val(elderlyInfo.householdRegister);//户籍
                    $("#age").val(elderlyInfo.age);
                     $("#userPid").val(elderlyInfo.userPid);
                    $("#nation").val(elderlyInfo.nation);//民族
                    $("#liveAddress").val(elderlyInfo.liveAddress);//居住地址
                    $("#socialSecurityType").val(elderlyInfo.socialSecurityType);//社保类型
                    $("#socialSecurityCardNo").val(elderlyInfo.socialSecurityCardNo);//社保卡号
                    $("#education").val(elderlyInfo.education);//文化程度
                    $("#retireCompany").val(elderlyInfo.retireCompany);//退休单位
                    $("#occupation").val(elderlyInfo.occupation);//职业
                    $("#nativePlace").val(elderlyInfo.nativePlace);//籍贯
                    //认知情况
                    if (!isNull(elderlyInfo.cognitionStatus)) {
                        $("input[name=cognitionStatus][value='" + elderlyInfo.cognitionStatus + "']").prop('checked', true);
                    }
                    //头像图片
                    if (!isNull(elderlyInfo.imgPath)) {
                        $('#imgPath').attr('value', elderlyInfo.imgPath);
                        $('#imgPath').attr('src', elderlyInfo.imgPath);
                    }

                    //*****主要联系人********
                    if (!isNull(elderlyInfo.userInfoContactList)) {
                        for (var i = 0; i < elderlyInfo.userInfoContactList.length; i++) {
                            var userInfoContact = elderlyInfo.userInfoContactList[i];
                            initUserInfoContact(i + 1, userInfoContact)
                        }
                    }
                } else {

                }
            }
        });
    }


    //初始化联系人
    function initUserInfoContact(num, userInfoContact) {
        $("#contactName" + num).val(userInfoContact.contactName);//联系人姓名
        $("#mobile" + num).val(userInfoContact.mobile);//手机号

    }


    function back() {
        window.history.back();
    }

    //确认保存
    function confirmAdd() {

    	var userNo = $("#userNo").val();
        //==============基本信息=================================
        var userName = $("#userName").val();//姓名
        var cognitionStatus = $("input:radio[name='cognitionStatus']:checked").val();//认知
        var userSex = $("#userSex").val();//性别
        var nation = $("#nation").val();//民族
        var householdRegister = $("#householdRegister").val();//户籍类型
        var userPid = $("#userPid").val();//身份证号
        var age = $("#age").val();//年龄
        var education = $("#education").val();//文化程度
        var nativePlace = $("#nativePlace").val();//籍贯
        var liveAddress = $("#liveAddress").val();//家庭地址
        var socialSecurityType = $("#socialSecurityType").val();//社保类型
        var socialSecurityCardNo = $("#socialSecurityCardNo").val();//社保卡号
        var retireCompany = $("#retireCompany").val();//工作单位
        var occupation = $("#occupation").val();//职业
        var imgPath = $("#imgPath").attr("value"); //头像

        if (isNull(userName)) {
            layer.msg("姓名不能为空", {time: 2000});
            return;
        } else if (userName.length > 14) {
            layer.msg("姓名过长", {time: 2000});
            return;
        }

        if (isNull(nation)) {
            layer.msg("民族不能为空", {time: 2000});
            return;
        }
        if (isNull(householdRegister)) {
            layer.msg("户籍类型不能为空", {time: 2000});
            return;
        }
        if (isNull(userPid)) {
            layer.msg("身份证号不能为空", {time: 2000});
            return;
        } else if (userPid.length > 18) {
            layer.msg("身份证号过长", {time: 2000});
            return;
        }else if(!checkUserPid(userPid)){
			layer.msg('请填写正确的身份证', {time: 2000});
			return;
		}

        if (isNull(userSex)) {
            layer.msg("性别不能为空", {time: 2000});
            return;
        }
        if (!isNull(nativePlace)) {
            if (nativePlace.length > 20) {
                layer.msg("籍贯过长", {time: 2000});
                return;
            }
        }
        if (isNull(liveAddress)) {
            layer.msg("家庭地址不能为空", {time: 2000});
            return;
        } else if (liveAddress.length > 50) {
            layer.msg("家庭地址过长", {time: 2000});
            return;
        }
        if (isNull(socialSecurityType)) {
            layer.msg("社保类型不能为空", {time: 2000});
            return;
        }

        if (isNull(socialSecurityCardNo)) {
            layer.msg("社保卡号不能为空", {time: 2000});
            return;
        } else if (socialSecurityCardNo.length > 20) {
            layer.msg("社保卡号过长", {time: 2000});
            return;
        }
        if (!isNull(retireCompany)) {
            if (retireCompany.length > 20) {
                layer.msg("工作单位过长", {time: 2000});
                return;
            }
        }
        if (!isNull(occupation)) {
            if (occupation.length > 20) {
                layer.msg("职业过长", {time: 2000});
                return;
            }
        }


        //========================紧急联系人=======================
        //联系人   1号
        var contactName1 = $("#contactName1").val();
        var mobile1 = $("#mobile1").val();
        //联系人   2号
        var contactName2 = $("#contactName2").val();
        var mobile2 = $("#mobile2").val();
        //联系人   3号
        var contactName3 = $("#contactName3").val();
        var mobile3 = $("#mobile3").val();
        //联系人   4号
        var contactName4 = $("#contactName4").val();
        var mobile4 = $("#mobile4").val();
        //紧急联系人必填一条
        if (isNull(contactName1) && isNull(mobile1)
            && isNull(contactName2) && isNull(mobile2)
            && isNull(contactName3) && isNull(mobile3)
            && isNull(contactName4) && isNull(mobile4)) {
            layer.msg("请至少输入一个紧急联系人", {time: 2000});
            return;
        }
        var a1 = checkContactPeople("一", contactName1, mobile1);
        var a2 = checkContactPeople("一", contactName2, mobile2);
        var a3 = checkContactPeople("一", contactName3, mobile3);
        var a4 = checkContactPeople("一", contactName4, mobile4);
        if (!a1 || !a2 || !a3 || !a4) {
            return;
        }


        //============================整理数据=========================================
        //获取联系人 list
        var userInfoContactList = [];
		if (!isNull(mobile1)) {
			var userInfoContact = getUserInfoContact(contactName1,mobile1);
			userInfoContactList.push(userInfoContact);
		}
		if (isNull(mobile2) ) {
			var userInfoContact = getUserInfoContact(contactName2,mobile2);
			userInfoContactList.push(userInfoContact);
		}
		if (isNull(mobile3) ) {
			var userInfoContact = getUserInfoContact(contactName3,mobile3);
			userInfoContactList.push(userInfoContact);
		}
		if (isNull(mobile4) ) {
			var userInfoContact = getUserInfoContact(contactName4,mobile4);
			userInfoContactList.push(userInfoContact);
		}


        var formDate =
            {
            	userNo : userNo,
                //=====基本信息=========
                userName: userName,
                cognitionStatus: cognitionStatus,
                userSex: userSex,
                nation: nation,
                householdRegister: householdRegister,
                userPid: userPid,
                age: age,
                education: education,
                nativePlace: nativePlace,
                liveAddress: liveAddress,
                socialSecurityType: socialSecurityType,
                socialSecurityCardNo: socialSecurityCardNo,
                retireCompany: retireCompany,
                occupation: occupation,
                imgPath: imgPath,
                userInfoContactList: userInfoContactList,//紧急联系人

            };

        $.ajax({
            url: "../elderlyInfo/updateYlElderlyInfoByUserNo",
            type: "post",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(formDate),
            success: function (data) {
                console.log(data);
                if (data.code == "200") {
                    layer.msg('修改成功', {icon: 1, time: 1500}, function () {
                        window.location.href = "../elderlyInfo/jumpElderlyInfoList";
                    });
                } else {
                    layer.msg(data.msg, {icon: 2});
                }
            }
        });
    }


    //获取联系人 对象
    function getUserInfoContact(contactName, mobile) {
        return {"contactName": contactName, "mobile": mobile};
    }


    //联系人 姓名可以为空 联系电话不能为空
    function checkContactPeople(contactNum, name, mobile) {
        if (!isNull(name)) {
            if (isNull(mobile)) {
                layer.msg("第" + contactNum + "联系人," + "请输入联系电话", {time: 2000});
                return false;
            } else {
                if (!isPhoneNumber(mobile)) {
                    layer.msg("第" + contactNum + "联系人," + "手机号输入错误", {time: 2000});
                    return false;
                }
            }
        }
        return true;
    }


    //通过身份证计算年龄
    function getAgeByIdCard(UUserCard) {
        //获取年龄
        var myDate = new Date();
        var month = myDate.getMonth() + 1;
        var day = myDate.getDate();
        var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
        if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
            age++;
        }
        return age;
    }

    function changeNum(obj) {
        //如果用户第一位输入的是小数点，则重置输入框内容
        if (obj.value != '' && obj.value.substr(0, 1) == '.') {
            obj.value = "";
        }
        //粘贴不生效
        obj.value = obj.value.replace(/^0*(0\.|[1-9])/, '$1');
        //清除“数字”和“.”以外的字符
        obj.value = obj.value.replace(/[^\d.]/g, "");
        //只保留第一个. 清除多余的
        obj.value = obj.value.replace(/\.{2,}/g, ".");
        obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        //只能输入两个小数
        obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
        if (obj.value.indexOf(".") < 0 && obj.value != "") {
            //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
            if (obj.value.substr(0, 1) == '0' && obj.value.length == 2) {
                obj.value = obj.value.substr(1, obj.value.length);
            }
        }
    }

    function isNull(value) {
        return value == null || value === "" || value === undefined;
    }

    /**判断是否是手机号**/
    function isPhoneNumber(tel) {
        var reg = /^0?1[3|4|5|6|7|8][0-9]\d{8}$/;
        return reg.test(tel);
    }

    //检查身份证号码是否符合规范，包括长度，类型
	function checkUserPid(card)
	{
	    //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
	    var reg = /(^\d{15}$)|(^\d{17}(\d|X|x)$)/;
	    if(reg.test(card) === false)
	    {
	        return false;
	    }
	    return true;
	};


</script>
</body>

</html>
